<template>
  <div class="AddOrUpdate_main add_container column_one">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">

        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="formData.fileName" clearable readonly placeholder="点击选择文件" @click.native="upload" />
        </el-form-item>

        <el-form-item label="版本号" prop="fileVersion">
          <el-input v-model="formData.fileVersion" clearable placeholder="请输入" />
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>

    <input ref="upload" type="file" style="display: none" @change="handleFileChange">
  </div>
</template>

<script>
import { getFileSize } from '@/utils/tool'
import { getToken } from '@/utils/auth'
import axios from 'axios'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: '',
        fileName: '',
        fileVersion: ''
      },
      rules: {
        fileName: [
          { required: true, message: '请选择文件', trigger: 'change' }
        ],
        fileVersion: [
          { required: true, message: '版本号不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const formData = new FormData()
          formData.append('file', this.file)
          // formData.append('fileName', this.formData.fileName)
          formData.append('fileVersion', this.formData.fileVersion)
          formData.append('fileSize', this.formData.fileSize)

          const config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              Authorization: getToken()
            }
          }
          axios.post('/common/iot/deviceFile/add', formData, config).then(res => {
            switch (res.data.code) {
              case 200:
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                })
                this.$layer.close(this.layerid)// 关闭弹框
                this.$parent.getList()// 调用父组件的刷新方法
                break
              default:
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                })
            }
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    upload() {
      this.$refs.upload.click()
    },
    handleFileChange(e) {
      const files = e.target.files
      this.file = files[0]
      this.formData.fileName = files[0].name
      this.formData.fileSize = getFileSize(this.file.size)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
